<template>
  <div class="app-container">

    <!-- 表头 查询与新增 -->
    <el-row>
      <el-col :span="24">
        <div class="filter-container">
          <el-select v-if="isAdminUser" v-model="listQuery.shopId" placeholder="请选择门店">
            <el-option v-for="item in shopData" :key="item.shopId" :value="item.shopId" :label="item.shopName"/>
          </el-select>
          <el-date-picker
            v-model="listQuery.scheduleDay"
            value-format="timestamp"
            type="date"
            placeholder="选择日期"/>
          <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
          <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-circle-plus-outline" @click="handleCreate">新增</el-button>
        </div>
      </el-col>
    </el-row>

    <!-- 表格list -->
    <el-row>
      <el-col :span="24" :gutter="24">
        <el-table
          v-loading="listLoading"
          :key="tableKey"
          :data="list"
          :height="tableHeight"
          element-loading-text="Loading"
          border
          fit
          style="width: 100%;"
          highlight-current-row>
          <el-table-column align="center" label="序号" width="80">
            <template slot-scope="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column label="所属分店" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.shopName }}
            </template>
          </el-table-column>
          <el-table-column label="排班日期" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.scheduleDay | timeFilter }}
            </template>
          </el-table-column>
          <el-table-column label="开始时间" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.startTime | timeFilter }}
            </template>
          </el-table-column>
          <el-table-column label="限号" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.apLimit }}
            </template>
          </el-table-column>
          <el-table-column label="结束时间" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.endTime | timeFilter }}
            </template>
          </el-table-column>
          <el-table-column class-name="status-col" label="有效标志" style="width: 10%" align="center">
            <template slot-scope="scope">
              <el-tag :type="scope.row.validFlag | statusFilter">{{ scope.row.validFlag | validFilter }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="180" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="primary" @click="handleUpdate(scope.row)">
                编辑
              </el-button>
              <el-button size="mini" type="danger" @click="handleDelete(scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="listQuery.pageNum"
          :limit.sync="listQuery.pageSize"
          layout="total, sizes, prev, pager, next"
          style="float:right;"
          @pagination="fetchData"/>
      </el-col>
    </el-row>

    <!-- 编辑弹窗 -->
    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      width="70%">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="right"
        label-width="100px"
        style="">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="门店名称" label-width="105px" prop="shopId">
              <el-select :disabled="!isAdminUser" v-model="temp.shopId" placeholder="请选择门店">
                <el-option v-for="item in shopData" :key="item.shopId" :value="item.shopId" :label="item.shopName"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="dialogStatus == 'update'" label="排班日期" label-width="105px" prop="scheduleDay">
              <el-date-picker
                v-model="temp.scheduleDay"
                value-format="timestamp"
                type="date"
                placeholder="选择排班日期"/>
            </el-form-item>
            <el-form-item v-if="dialogStatus == 'create'" label="排班日期" label-width="105px">
              <el-date-picker
                v-model="temp.rangeSceduleDay"
                value-format="timestamp"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="限号" label-width="105px" prop="apLimit">
              <el-input v-model.number="temp.apLimit"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="间隔时间(分)" label-width="105px" prop="timeInterval">
              <el-input v-model.number="temp.timeInterval"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="时间范围" label-width="105px">
              <el-time-picker
                v-model="rangeData"
                is-range
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                placeholder="选择时间范围"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="有效标志" label-width="105px">
              <el-switch
                v-model="validSwitch"
                active-color="#13ce66"
                inactive-color="#ff4949"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">确认</el-button>
        <el-button @click="dialogFormVisible = false">取消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import SxScheduleInfoApi from '@/api/manage/SxScheduleInfoApi'
import sxProductBasicInfoApi from '@/api/manage/SxProductBasicInfoApi'
import SxShopInfoApi from '@/api/manage/SxShopInfoApi'
import waves from '@/directive/waves' // Waves directive
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
export default {
  directives: { waves },
  components: { Pagination },
  filters: {
    statusFilter(status) {
      const statusMap = {
        1: 'success',
        2: 'gray',
        0: 'danger'
      }
      return statusMap[status]
    },
    validFilter(status) {
      const statusMap = {
        1: '有效',
        0: '作废'
      }
      return statusMap[status]
    },
    timeFilter(time) {
      if (time) {
        return new Date(time).Format('yyyy-MM-dd hh:mm:ss')
      } else {
        return ''
      }
    }
  },
  data() {
    return {
      tableKey: 0, // 表格key值
      list: null, // 表格对象
      listLoading: true, // 表格加载框
      shopData: [],
      productData: [],
      total: 0, // 分页总数
      tableHeight: window.innerHeight - 220, // 表格高度
      listQuery: { // 表格查询对象
        pageNum: 1,
        pageSize: 10,
        query: '',
        scheduleId: null,
        shopId: null,
        scheduleDay: null
      },
      temp: {}, // 编辑框临时变量
      statusOptions: { // 有效无效下拉框
        '1': '有效',
        '0': '作废'
      },
      dialogFormVisible: false, // 编辑框显示
      dialogStatus: '', // 编辑框更新插入状态
      textMap: { // 编辑框标题
        update: '编辑',
        create: '创建'
      },
      rules: { // 编辑框校验规则
        shopId: [{ required: true, message: '不能为空' }],
        scheduleDay: [{ required: true, message: '不能为空' }],
        apLimit: [{ type: 'number', message: '必须为数字' },
          { required: true, message: '不能为空' }],
        timeInterval: [{ type: 'number', message: '必须为数字' }, { required: true, message: '不能为空' }]
      },
      rangeData: this.getRangeData()
    }
  },
  computed: {
    listQueryParam() {
      const param = this.$_.assignIn({}, this.listQuery)
      if (!this.isAdminUser) {
        param['shopId'] = this.ownShopId
      }
      return param
    },
    ownShopId() {
      return this.$store.getters.manageShop
    },
    isAdminUser() {
      if (this.ownShopId === '' || this.ownShopId === '1') {
        return true
      }
      return false
    },
    startTime() {
      let startTime = new Date()
      if (this.temp.scheduleDay) {
        startTime = new Date(this.temp.scheduleDay)
      }
      let hours = 8
      let second = 0
      let minutes = 0
      if (this.rangeData[0]) {
        const tempDate = this.rangeData[0]
        hours = tempDate.getHours()
        minutes = tempDate.getMinutes()
        second = tempDate.getSeconds()
      }
      startTime.setHours(hours)
      startTime.setMinutes(minutes)
      startTime.setSeconds(second)
      return startTime.getTime()
    },
    endTime() {
      let startTime = new Date()
      if (this.temp.scheduleDay) {
        startTime = new Date(this.temp.scheduleDay)
      }
      let hours = 8
      let second = 0
      let minutes = 0
      if (this.rangeData[1]) {
        const tempDate = this.rangeData[1]
        hours = tempDate.getHours()
        minutes = tempDate.getMinutes()
        second = tempDate.getSeconds()
      }
      startTime.setHours(hours)
      startTime.setMinutes(minutes)
      startTime.setSeconds(second)
      return startTime.getTime()
    },
    validSwitch: {
      // getter
      get: function() {
        return this.temp.validFlag === '1'
      },
      // setter
      set: function(newValue) {
        if (newValue) {
          this.temp.validFlag = '1'
        } else {
          this.temp.validFlag = '0'
        }
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    getRangeData() {
      const startTime = new Date()
      const endTime = new Date()
      startTime.setHours(8)
      startTime.setMinutes(0)
      startTime.setSeconds(0)
      endTime.setHours(22)
      endTime.setMinutes(0)
      endTime.setSeconds(0)
      return [startTime, endTime]
    },
    /**
     * 获取门店地址
     * */
    getShopData() {
      SxShopInfoApi.getList({ r: Math.random() }).then(data => {
        this.shopData = data
      })
    },
    /**
     * 获取顶级结点
     * */
    getProductData() {
      sxProductBasicInfoApi.getRootData({ r: Math.random() }).then((data) => {
        this.productData = data
      })
    },
    /**
       * 获取表格数据
       */
    fetchData() {
      const that = this
      this.listLoading = true
      if (this.isAdminUser) {
        this.getShopData()
      }
      this.$http.all([SxScheduleInfoApi.getPage(this.listQueryParam)])
        .then(this.$http.spread(function(perms) {
          that.list = perms.rows
          that.total = perms.total
          that.listLoading = false
        }))
    },
    /**
       * 新增弹窗
       */
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.getProductData()
      this.getShopData()
      if (!this.isAdminUser) {
        this.temp.shopId = this.ownShopId
      }
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    /**
       * 清空弹窗内容
       */
    resetTemp() {
      this.temp = {
        scheduleId: '',
        shopId: '',
        pid: '',
        rangeSceduleDay: [],
        scheduleDay: '',
        scheduleType: '',
        timeInterval: 15,
        createdTime: '',
        modifiedTime: '',
        startTime: '',
        endTime: '',
        apLimit: 1,
        validFlag: '1'
      }
    },
    /**
       * 确定新增
       */
    createData() {
      debugger
      const that = this
      this.temp.startTime = this.startTime
      this.temp.endTime = this.endTime
      if (this.temp.rangeSceduleDay.length == 2) {
        this.temp.scheduleDay = this.temp.rangeSceduleDay[0]
        this.temp.startScheduleDay = this.temp.rangeSceduleDay[0]
        this.temp.endScheduleDay = this.temp.rangeSceduleDay[1]
      }
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          SxScheduleInfoApi.insert(this.temp).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 1000,
              onClose() {
                that.fetchData()
              }
            })
          })
        }
      })
    },
    /**
       * 编辑弹窗
       */
    handleUpdate(row) {
      this.temp = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.getProductData()
      this.getShopData()
      this.rangeData = [new Date(this.temp.startTime), new Date(this.temp.endTime)]
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    /**
       * 确认编辑
       */
    updateData() {
      const that = this
      this.temp.startTime = this.startTime
      this.temp.endTime = this.endTime
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          SxScheduleInfoApi.update(tempData).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 1000,
              onClose() {
                that.fetchData()
              }
            })
          })
        }
      })
    },
    /**
       * 删除操作
       */
    handleDelete(row) {
      const that = this
      SxScheduleInfoApi.remove(row).then(() => {
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 1000,
          onClose() {
            that.fetchData()
          }
        })
      })
    },
    /**
       * 搜索过滤
       */
    handleFilter() {
      this.listQuery.pageNum = 1
      this.fetchData()
    }
  }
}
</script>
